import 'dart:async';
import 'dart:convert';
import 'package:aitao_flutter/config/config.dart';
import 'package:aitao_flutter/im/im_manager.dart';
import 'package:aitao_flutter/model/login_user_info.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../const/common_const.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../routes/routes.dart';
import '../../utils/log_utils.dart';
import '../../utils/sp_utils.dart';

class CodeLoginController extends GetxController {
  TextEditingController phoneController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  bool isCountingDown = false;
  String lastPhone = '';
  int countdownSeconds = 60;
  Timer? timer;
  Fluwx fluwx = Fluwx();
  loginClick() async {
    if (!GetUtils.isPhoneNumber(phoneController.text)) {
      EasyLoading.showToast(LoginStringConst.inputCorrectPhone);
      return;
    }
    if (codeController.text.isEmpty || codeController.text.length <= 4) {
      EasyLoading.showToast(LoginStringConst.inputVerCodeText);
      return;
    }
    var result = await RequestManager().post(API.loginBySmsCode, params: {
      'phone_code': codeController.text,
      'mobile': phoneController.text
    });
    WJLogUtils.wjLog(result);
    if (result != null && result['code'] == 0) {
      LoginUserInfo userInfo =
          LoginUserInfo.fromJson(result['data']['userinfo']);
      EasyLoading.showToast('登录成功');
      saveLoginUserInfo(userInfo);
      Get.toNamed(Routes.tabPage, preventDuplicates: false);
      // 同时登录IM
      if (userInfo.imToken != null && userInfo.userId != null) {
        loginIM(userInfo.imToken!, userInfo.userId!.toString());
      }
    } else {
      EasyLoading.showToast('登录失败');
      // StoreUtils.cleanData();
    }
  }

  /// 登录IM
  void loginIM(String token, String account) {
    debugPrint('登录IM');
    IMManager.getInstance()?.imLogin(account, token);
  }

  /// 微信登录
  wechatLoginClick() {
    debugPrint('微信登录');

    fluwx.authBy(
        which: NormalAuth(
            scope: 'snsapi_userinfo', state: 'wechat_sdk_demo_test'));
  }

  /// 密码登录
  passwordLoginClick() {
    Get.toNamed(Routes.passwordLoginPage);
  }

  /// 保存用户信息
  saveLoginUserInfo(LoginUserInfo userInfo) {
    if (userInfo.token != null) {
      // 保存用户token
      SpUtil.saveToken(userInfo.token!);
      // 保存IM
      SpUtil.saveIMToken(userInfo.imToken!);
    }
    // 保存上次登录手机号
    SpUtil.saveLastLoginPhone(userInfo.mobile ?? '');
    // 保存用户信息
    SpUtil.saveLoginUserInfo(userInfo);
  }

  /// 获取验证码
  getSmsCode() async {
    if (!phoneController.text.isPhoneNumber) {
      EasyLoading.showToast(LoginStringConst.inputCorrectPhone);
      return;
    }
    if (isCountingDown) return;
    startCountdown();

    var result =
        await RequestManager().post(API.getSmsCode, params: {'type': 'login'});
    if (result != null && result['code'] == 200) {
      EasyLoading.showToast('验证码已发送');
    }
  }

  /// 开始倒计时
  void startCountdown() {
    isCountingDown = true;
    countdownSeconds = 10;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdownSeconds--;
      update();
      if (countdownSeconds <= 0) {
        isCountingDown = false;
        timer.cancel();
      }
    });
  }

  @override
  void onInit() {
    super.onInit();
    getLastPhone();
    fluwx.addSubscriber((response) async {
      WeChatAuthResponse r = response as WeChatAuthResponse;
      if (r.errCode == 0) {
        String code = r.code!;
        Map<String, dynamic> params = {
          'appid': AppConfig.wxAppKey,
          'secret': AppConfig.wxAppSecret,
          'code': code,
          'grant_type': 'authorization_code'
        };
        var result = await Dio().post(
            'https://api.weixin.qq.com/sns/oauth2/access_token',
            queryParameters: params);
        Map loginData = json.decode(result.data);
        String openid = loginData['openid'];

        String accessToken = loginData['access_token'].toString();

        Map wxParams = {
          'platform': 'wechat',
          'openid': openid,
          'access_token': accessToken
        };
        var loginResult =
            await RequestManager().post(API.loginBythird, params: wxParams);
        WJLogUtils.wjLog(loginResult);
        if (loginResult != null && loginResult['code'] == 0) {
          LoginUserInfo userInfo =
              LoginUserInfo.fromJson(loginResult['data']['userinfo']);
          EasyLoading.showToast('登录成功');
          getUploadConfig();
          saveLoginUserInfo(userInfo);
          Get.toNamed(Routes.tabPage, preventDuplicates: false);
          // 同时登录IM
          if (userInfo.imToken != null && userInfo.userId != null) {
            loginIM(userInfo.imToken!, userInfo.userId!.toString());
          }
        }

        // EasyLoading.showToast("用户授权");
      } else if (r.errCode == -4) {
        EasyLoading.showToast("用户拒绝授权");
      } else if (r.errCode == -2) {
        EasyLoading.showToast("用户取消");
      }
    });
  }

  void getUploadConfig() async {
    var result =
        await RequestManager().get(API.getUploadConfig, hasCode: false);
    if (result != null && result['StatusCode'] == 200) {
      SpUtil.saveOssConfig(result);
    }
  }

  // 获取上次登录的手机号
  void getLastPhone() {
    String phone = SpUtil.getLastLoginPhone();
    if (phone != '') {
      lastPhone = phone;
      update();
    }
  }
}
